package com.hfi.restful.web.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ChangLiang
 * @date 2019/7/31
 */
@Component
public class TimeInterceptor implements HandlerInterceptor {

    private Logger LOGGER = LoggerFactory.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOGGER.info("preHandle");

        LOGGER.info(((HandlerMethod) handler).getBean().getClass().getName());
        LOGGER.info(((HandlerMethod) handler).getMethod().getName());

        request.setAttribute("startTime",System.currentTimeMillis());
        // 控制是不是调用handler false--不调用 true--调用
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        LOGGER.info("postHandle");
        Long startTime = (Long) request.getAttribute("startTime");
        LOGGER.info("time interceptor postHandler耗时" + (System.currentTimeMillis() - startTime) + "ms");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LOGGER.info("afterCompletion");
        Long startTime = (Long) request.getAttribute("startTime");
        LOGGER.info("time interceptor afterCompletion耗时" + (System.currentTimeMillis() - startTime) + "ms");
        LOGGER.info("ex is " + ex);
    }
}
